using Mono.Cecil.Cil;

namespace Cil.Ast;

public sealed class IfElseExpression : BranchingExpression
{
	public const int ConditionPos = 0;
	public const int TrueExpressionPos = 1;
	public const int FalseExpressionPos = 2;
	public const int MaxNodes = 3;

	public IfElseExpression(Context context, Instruction target, ConditionExpression exp_condition, Expression exp_ontrue, Expression exp_onfalse) : base(context, target)
	{
		Nodes = new FixedList<Expression>(MaxNodes);
		Context.SetExpression(target, this);
		Condition = exp_condition;
		TrueExpression = exp_ontrue;
		FalseExpression = exp_onfalse;
	}

	public ConditionExpression Condition { get { return (ConditionExpression) Nodes[ConditionPos]; } private set { Nodes[ConditionPos] = value; value.ParentNode = this; } }

	public Expression TrueExpression { get { return Nodes[TrueExpressionPos]; } private set { Nodes[TrueExpressionPos] = value; value.ParentNode = this; } }

	public Expression FalseExpression { get { return Nodes[FalseExpressionPos]; } private set { Nodes[FalseExpressionPos] = value; value.ParentNode = this; } }

	public override string ToString()
	{
		var sb = new System.Text.StringBuilder();
		sb.Append("if(");
		sb.Append(Condition.ToString());
		sb.Append(") {");
		sb.AppendLine();
		sb.Append(TrueExpression.ToString());
		sb.AppendLine("}");
		if (!FalseExpression.IsEmpty)
		{
			sb.AppendLine("else {");
			sb.Append(FalseExpression.ToString());
			sb.AppendLine("}");
		}
		return sb.ToString();
	}
}